package fr.mistra.exercice.bibliotheque.presentation;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet Filter implementation class AuthFilter
 */
public class AuthFilter implements Filter {

    /**
     * Default constructor. 
     */
    public AuthFilter() {
    	//Vide
    }

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		//TODO implementer si n�cessaire
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req	= (HttpServletRequest) request;
		HttpServletResponse res	= (HttpServletResponse) response;

		String urlRelative = req.getServletPath();
		boolean interception=false;
		
		if (! (	urlRelative.equals("/AuthentificationServlet") ||
				urlRelative.equals("/index.jsp") ||
				urlRelative.equals("/erreur.jsp") ) ) {
			//On ne cherche pas � s'authentifier... Donc, soit on est authentifi�, soit on est vir�.
			HttpSession s = req.getSession(false);
			if (s == null) {
				System.out.println("Pas de session, redirection !");
//				res.sendRedirect("erreur.jsp");
				interception=true;
				//La ligne suivante :
				res.sendRedirect("erreur.jsp");
				//equivaut � : request.getRequestDispatcher("erreur.jsp").forward(request, response);
			}
			else
			{
				String login = (String) s.getAttribute("login");
				System.out.println("Login : " + login);
				if (login == null) {
					System.out.println("Session non authentifi�e, redirection !");
					interception=true;
					res.sendRedirect("erreur.jsp");
				}
			}
		}
		if (!interception) chain.doFilter(request, response);		
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		//TODO impl�menter si n�cessaire
	}
}
